package com.monad.firemoth.config.satoken.interceptor;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.monad.firemoth.common.utils.Result;
import com.monad.firemoth.system.entity.User;
import com.monad.firemoth.system.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.PrintWriter;

/**
 * @author 单C胞生物
 * @version 1.0.0
 * @date 2024/4/21 16:22
 * @description 登录拦截器
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json");
        PrintWriter writer = response.getWriter();
        if (StpUtil.isLogin()) {
            String token = request.getParameter("Authorization");
            if (token == null) {
                token = request.getHeader("Authorization");
                if (token == null) {
                    Result error = Result.error(401, "未检测到token!");
                    writer.write(new ObjectMapper().writeValueAsString(error));
                    writer.flush();
                    writer.close();
                    return false;
                }
            }
            if (token.equals(StpUtil.getTokenValue())) {
                User user = userService.getOne(Wrappers.lambdaQuery(User.class).eq(User::getUserId, StpUtil.getLoginId()));
                if (user.getEnabled() == 1) {
                    Result error = Result.error(401, "账号已停用!");
                    writer.write(new ObjectMapper().writeValueAsString(error));
                    writer.flush();
                    writer.close();
                    return false;
                } else {
                    return true;
                }
            } else {
                Result error = Result.error(401, "非法token!");
                writer.write(new ObjectMapper().writeValueAsString(error));
                writer.flush();
                writer.close();
                return false;
            }
        } else {
            Result error = Result.error(401, "用户未登录，请先登录!");
            writer.write(new ObjectMapper().writeValueAsString(error));
            writer.flush();
            writer.close();
            return false;
        }
    }
}
